package com.moorror.codegenvel.common.tree.actions;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAware;
import com.moorror.codegenvel.common.dialog.DialogFormTable;
import com.moorror.codegenvel.common.dialog.MRDialog;
import com.moorror.codegenvel.utils.SQLUtils;
import com.moorror.codegenvel.view.window.codegen.domain.ColumnDesc;
import com.moorror.codegenvel.view.window.codegen.domain.TableDesc;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.function.Consumer;

/**
 * @Author jiyanghuang
 * @Date 2025/8/24 17:38
 */
public class SQLConfigAction extends AnAction implements DumbAware {

    private final Editor editor;
    private final Consumer<TableDesc> consumer;
    private int prefixLen = 0;
    public SQLConfigAction(Editor editor, Consumer<TableDesc> consumer) {
        super("Compile SQL", "解析SQL", AllIcons.Actions.Compile);
        this.editor = editor;
        this.consumer = consumer;
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        String sql = editor.getDocument().getText();
        TableDesc tableDesc = SQLUtils.parser(sql, prefixLen);
        if(null != tableDesc){
            DialogFormTable dialogFormTable = new DialogFormTable(e.getProject(),"", ColumnDesc.class, tableDesc.getFullColumn(), (s) -> {
                tableDesc.setFullColumn((List)s);
                consumer.accept(tableDesc);
            });
            MRDialog.of(dialogFormTable).show();
        }
    }

    public void fillPrefixLen(String num){
        if(StringUtils.isBlank(num)){
            return;
        }
        prefixLen = Integer.valueOf(num);
    }
}
